﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace MeiRiCai.Sdk.Core
{
	public static class SdkUtils
	{
		/// <summary>
		/// 获得Uri
		/// </summary>
		/// <param name="path">资源路径，如/user/info</param>
		/// <param name="queryParams">查询参数</param>
		/// <returns>返回Uri实例</returns>
		public static Uri GetUri(String path, Dictionary<String, Object> queryParams)
		{
			UriBuilder uriBuilder = new UriBuilder(SdkConfig.BaseAddress);
			uriBuilder.Path = path;
			uriBuilder.Query = GetQuery(queryParams);
			return uriBuilder.Uri;
		}

		/// <summary>
		/// 获得查询字符串
		/// </summary>
		/// <param name="queryParams">查询参数</param>
		/// <returns>返回查询字符串</returns>
		public static String GetQuery(Dictionary<String, Object> queryParams)
		{
			String query = "";
			foreach (var kv in queryParams)
			{
				String kvString = HttpUtility.UrlEncode(kv.Key) + "=" + HttpUtility.UrlEncode(kv.Value.ToString());
				if (query == "")
				{
					query = kvString;
				}
				else
				{
					query = query + "&" + kvString;
				}
			}
			return query;
		}

		/// <summary>
		/// 使用GET方法请求
		/// </summary>
		/// <typeparam name="T">反序列化对象类型</typeparam>
		/// <param name="path">资源路径，如/user/info</param>
		/// <param name="queryParams">查询参数</param>
		/// <returns></returns>
		public static T GetFromUrl<T>(String path, Dictionary<String, Object> queryParams)
		{
			Uri uri = GetUri(path, queryParams);
			String json = OauthUtils.GetHttpBodyText(uri);
			return JsonConvert.DeserializeObject<T>(json);
		}
	}
}
